package _interview150;

import java.util.ArrayList;
import java.util.List;

/**
 * 39. 组合总和
 */
public class No39 {
    private List<List<Integer>> ans;
    private List<Integer> path;
    private int[] candidates;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        this.candidates = candidates;
        dfs(target, candidates.length - 1);
        return ans;
    }

    private void dfs(int target, int j) {
        if (target == 0) {
            ans.add(new ArrayList<>(path));
            return;
        } else if (target < 0 || j < 0) return;

        for (int i = j; i >= 0; i--) {
            path.add(candidates[i]);
            dfs(target - candidates[i], i);
            path.remove(path.size() - 1);
        }
    }
}
